"""
综合助手智能体实现
"""
import logging
import sys
import os
import asyncio
import base64
from typing import Any, Dict, AsyncGenerator, Optional
from uuid import uuid4

# 修复导入路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from openai import AsyncOpenAI
from common.task_manager import InMemoryTaskManager, AITaskManager, extract_text_from_part
from common.types import (
    AgentCard, AgentCapabilities, AgentSkill, AgentProvider, IframeData, IframeSecurity,
    Task, TaskStatus, TaskState, Message, TextPart, DataPart, FilePart, Artifact,
    TaskSendParams, TaskQueryParams, TaskNotFoundError, TaskStatusUpdateEvent, TaskArtifactUpdateEvent
)
from composite_agent.config import CompositeAgentSettings

logger = logging.getLogger(__name__)

def text_generator(text, chunk_size=5):
    for i in range(0, len(text), chunk_size):
        yield text[i:i + chunk_size]  # 每次返回一个片段

def stream_output_with_generator(text, chunk_size=5):
    for chunk in text_generator(text, chunk_size):
        print(chunk, end='', flush=True)
def file_to_base64(file_path: str) -> str:
    """
    将文件内容转换为 Base64 字符串

    Args:
        file_path: 文件的路径

    Returns:
        Base64 编码的字符串
    """
    try:
        with open(file_path, "rb") as file:  # 以二进制模式读取文件
            file_data = file.read()
            base64_data = base64.b64encode(file_data)  # 编码为 Base64
            return base64_data.decode("utf-8")  # 转换为 UTF-8 字符串
    except FileNotFoundError:
        logger.error(f"错误：文件 '{file_path}' 不存在")
        return ""
    except Exception as e:
        logger.error(f"错误：无法读取文件 - {e}")
        return ""

def get_iframe_data(data: dict) -> dict:
    """
    获取 Iframe 数据
    """
    iframe_data = IframeData(
        iframeId="unique_iframe_id_123",
        title="示例 Iframe",
        src="https://www.mastercom.cn/index",
        width="100%",
        height=600,
        allowFullscreen=True,
        interactionMode="interactive",
        security=IframeSecurity(
            allowedOrigins=["https://www.mastercom.cn/index"],
            requireAuth=False
        ),
        metadata=data
    )
    return dict(iframe_data)

def parse_form_submission(message: Optional[Message]) -> Optional[Dict[str, Any]]:
    """解析表单提交数据"""
    if not message or not message.parts:
        return None

    for part in message.parts:
        if hasattr(part, 'data') and isinstance(part.data, dict):
            # 检查metadata中的dataType是否为form_submission（注意是下划线）
            if hasattr(part, 'metadata') and isinstance(part.metadata, dict):
                if part.metadata.get('dataType') == 'form_submission':
                    # 根据A2A协议，data字段直接包含FormSubmissionData结构
                    # FormSubmissionData包含：formId, values, timestamp, metadata
                    form_submission_data = part.data

                    # 检查是否是我们期望的表单
                    if form_submission_data.get('formId') == 'cuisine_preference_form':
                        logger.info(f"检测到表单提交数据: {form_submission_data}")
                        return form_submission_data.get('values', {})
    return None

class CompositeAgent:
    """综合助手智能体"""
    
    def __init__(self, settings: CompositeAgentSettings):
        self.settings = settings
        
        # 创建OpenAI客户端
        self.ai_client = AsyncOpenAI(
            api_key=settings.openai_api_key,
            base_url=settings.openai_api_base
        )
        
        # 创建智能体卡片
        self.agent_card = self._create_agent_card()
        
        # 创建任务管理器
        self.task_manager = CompositeTaskManager(
            ai_client=self.ai_client,
            settings=self.settings,
            system_prompt=settings.system_prompt,
            model=settings.openai_model
        )

        # self.task_manager = AITaskManager(
        #     ai_client=self.ai_client,
        #     system_prompt=settings.system_prompt,
        #     model=settings.openai_model
        # )

        # self.task_manager = InMemoryTaskManager()
    
    def _create_agent_card(self) -> AgentCard:
        """创建智能体卡片"""
        
        # 定义技能
        skills = [
            AgentSkill(
                id="Composite-Skill",
                name="综合技能",
                description="返回代码工件内容，工件内容使用<artifacts>标签包裹。",
                tags=["综合", "汇总"],
                examples=[
                    "帮我输出综合智能体案例",
                    "帮我输出汇总智能体案例",
                ]
            )
        ]
        
        # 创建提供者信息
        provider = AgentProvider(
            organization="ML A2A System",
            url=f"http://{self.settings.client_host}:{self.settings.port}"
        )
        
        # 定义扩展信息
        extensions = [
        ]

        # 定义安全模式
        security_schemes = {
        }

        # 定义安全要求
        security = [
            {"apiKey": []}
        ]

        # 创建能力信息
        capabilities = AgentCapabilities(
            streaming=True,
            pushNotifications=False,
            stateTransitionHistory=True,
            extensions=extensions
        )

        return AgentCard(
            name=self.settings.agent_name,
            description=self.settings.agent_description,
            url=f"http://{self.settings.client_host}:{self.settings.port}",
            provider=provider,
            iconUrl=f"http://{self.settings.client_host}:{self.settings.port}/api/v1/icon?name=composite_agent",# 替换为实际的图标URL
            version=self.settings.agent_version,
            documentationUrl="https://docs.examplegeoservices.com/georoute-agent/api",# 替换为实际的文档URL
            capabilities=capabilities,
            securitySchemes=security_schemes,
            security=security,
            defaultInputModes=["text/plain", "application/json"],
            defaultOutputModes=["text/plain", "application/json", "text/csv"], 
            skills=skills
        )


class CompositeTaskManager(InMemoryTaskManager):
    """基于综合的任务管理器"""

    def __init__(self, ai_client, settings, system_prompt: str = "", model: str = "gpt-4o-mini"):
        super().__init__()
        self.ai_client = ai_client
        self.system_prompt = system_prompt
        self.model = model
        self.settings = settings
        self.session_states: Dict[str, Dict[str, Any]] = {}

    def get_session_state(self, context_id: str) -> Dict[str, Any]:
        """获取会话状态"""
        if context_id not in self.session_states:
            self.session_states[context_id] = {
                "interaction_count": 0,
                "cuisine_preference": None,
                "conversation_stage": "initial"  # initial, cuisine_selected, recipe_provided
            }
        return self.session_states[context_id]

    def update_session_state(self, context_id: str, updates: Dict[str, Any]):
        """更新会话状态"""
        session_state = self.get_session_state(context_id)
        session_state.update(updates)

    async def _execute_task(self, task: Task, message: Message):
        """使用AI执行任务"""
        try:
            # 获取会话状态
            context_id = task.contextId
            session_state = self.get_session_state(context_id)

            # 增加交互计数
            session_state["interaction_count"] += 1
            interaction_count = session_state["interaction_count"]

            logger.info(f"处理综合任务 - 会话ID: {context_id}, 交互次数: {interaction_count}")

            # 提取用户消息文本
            user_text = ""
            for part in message.parts:
                user_text += extract_text_from_part(part) + " "

            user_text = user_text.strip()
            logger.info(f"处理用户消息: {user_text}")

            form_data = parse_form_submission(message)
            has_form_submission = form_data is not None

            logger.info(f"是否包含表单提交数据: {has_form_submission}")

            if has_form_submission:
                logger.info(f"处理表单提交数据: {form_data}")
                logger.info("检测到表单提交，进入表单处理逻辑")
                await self.form_interactive_event(task, user_text, form_data)
                logger.info(f"会话状态更新为: {session_state}")
            else:
                await self.artifact_event(task)

                # await self.file_event(task)
                #
                # await self.image_event(task)
                #
                # await self.iframe_event(task)

                # user_text = "请简略介绍人工智能的基本概念和应用场景。"
                # async for chunk in self._call_ai_model(user_text):
                #     await self._emit_status_event(
                #         task,
                #         TaskState.WORKING,
                #         chunk,
                #         final=False
                #     )
                #     await asyncio.sleep(0.001)
                #
                # await self.form_event(task)

            await self._emit_status_event(
                task,
                TaskState.COMPLETED,
                {},  # 直接发送当前块的内容
                final=True
            )
        except Exception as e:
            logger.error(f"执行综合任务时发生错误: {e}")
            # 创建错误消息
            error_message = Message(
                role="agent",
                parts=[TextPart(text=f"处理请求时发生错误: {str(e)}")]
            )
            # 更新任务状态为失败
            await self._update_task_status(task.id, TaskState.FAILED, error_message)
            await self._emit_status_event(
                task,
                TaskState.COMPLETED,
                {},  # 直接发送当前块的内容
                final=True
            )

    async def _call_ai_model(self, user_text: str) -> AsyncGenerator[str, None]:
        """调用AI模型 - 以流式方式返回响应"""
        messages = [{
            "role": "system",
            "content": self.system_prompt
        }, {
            "role": "user",
            "content": user_text
        }]

        # 增强系统提示词，明确要求输出工件内容

        # 调用AI客户端，启用流式响应
        stream = await self.ai_client.chat.completions.create(
            model=self.model,
            messages=messages,
            max_tokens=2000,
            temperature=0.7,
            stream=True
        )

        # 流式处理响应
        async for chunk in stream:
            content = chunk.choices[0].delta.content
            if content:
                yield content

    async def image_event(self, task: Task):
        # 图片数据
        file_bytes = {'type': 'fileWithBytes', 'mimeType': "image/png", 'name': "首页.png"}
        file_path = os.path.join(self.settings.docs_path, "首页.png")
        logger.info(f"文件路径: {file_path}")
        base64_value = file_to_base64(file_path)
        file_bytes['bytes'] = base64_value

        event_message = {"file": file_bytes}
        await self._emit_status_event(
            task,
            TaskState.WORKING,
            event_message,
            final=False
        )
        await asyncio.sleep(0.001)

        response_message = Message(
            messageId=str(uuid4()),
            role="agent",
            parts=[FilePart(file=file_bytes)],
            contextId=task.contextId,
            taskId=task.id,
            kind='message'
        )

        # 添加AI回复到历史记录
        async with self.lock:
            if task.history is None:
                task.history = []
            task.history.append(response_message)

    async def file_event(self, task: Task):
        # 文件数据
        file_response = {'type': 'fileWithUri', 'mimeType': "text/plain"}
        file_response['name'] = "简介.docx"
        file_response[
            'uri'] = f"http://{self.settings.client_host}:{self.settings.port}/api/v1/file?path=composite_agent&name={file_response['name']}"
        event_message = {"file": file_response}
        await self._emit_status_event(
            task,
            TaskState.WORKING,
            event_message,
            final=False
        )
        await asyncio.sleep(0.001)

        response_message = Message(
            messageId=str(uuid4()),
            role="agent",
            parts=[FilePart(file=file_response)],
            contextId=task.contextId,
            taskId=task.id,
            kind='message'
        )

        # 添加AI回复到历史记录
        async with self.lock:
            if task.history is None:
                task.history = []
            task.history.append(response_message)

    async def iframe_event(self, task: Task):
        # iframe数据
        metadata = {"dataType": "iframe"}
        data_response = get_iframe_data(metadata)
        iframe = {"iframe": data_response}
        event_message = {"data": iframe}
        await self._emit_status_event(
            task,
            TaskState.WORKING,
            event_message,
            metadata=metadata,
            final=False
        )
        await asyncio.sleep(0.001)

        response_message = Message(
            messageId=str(uuid4()),
            role="agent",
            parts=[DataPart(data=iframe, metadata=metadata)],
            contextId=task.contextId,
            taskId=task.id,
            kind='message'
        )

        # 添加AI回复到历史记录
        async with self.lock:
            if task.history is None:
                task.history = []
            task.history.append(response_message)

    async def artifact_event(self, task: Task):
        parts = []

        msg_first = """下面是一个请假流程的工件样例，使用 md 格式表示。这个流程图展示了一个典型的企业请假审批流程，包含了主要的步骤和决策点。"""
        for chunk in text_generator(msg_first, chunk_size=5):
            event_message = {'type': 'message', 'text': chunk}
            await self._emit_status_event(
                task,
                TaskState.WORKING,
                event_message,
                final=False
            )
            await asyncio.sleep(0.001)

        parts.append(TextPart(text=msg_first))

        msg_artifact = """graph TD
                                    A[开始] --> B[提交申请]
                                    B --> C{部门经理审批}
                                    C -->|通过| D[人力资源备案]
                                    C -->|驳回| E[提交申请]
                                    D --> E[结束]
                    """
        for chunk in text_generator(msg_artifact, chunk_size=5):
            # artifactType?: string; // 工件类型（如'report'、'image'、'dataset'、'mermaid'等），我们自定义的扩展字段其他任意元数据
            event_message = {'type': 'artifact', 'name': "请假流程", 'description': "一个典型的企业请假审批流程",
                             'text': chunk, 'artifactType': 'mermaid', 'append': True, 'lastChunk': False}
            metadata = {'dataType': 'artifact', 'artifactType': 'mermaid'}
            await self._emit_status_event(
                task,
                TaskState.WORKING,
                event_message,
                metadata=metadata,
                final=False
            )
            await asyncio.sleep(0.001)  # 极短暂的延迟确保事件被处理

        # 工件数据
        event_message = {'type': 'artifact', 'name': "请假流程", 'description': "一个典型的企业请假审批流程",
                         'content': "", 'artifactType': 'mermaid', 'append': False, 'lastChunk': True}
        metadata = {'dataType': 'artifact', 'artifactType': 'mermaid'}
        await self._emit_status_event(task, TaskState.WORKING, event_message, metadata=metadata, final=False)
        await asyncio.sleep(0.001)

        response_artifact = Artifact(name=event_message.get('name'),
                                     description=event_message.get('description'),
                                     parts=[TextPart(text=msg_artifact)],
                                     metadata=metadata,
                                     index=0,
                                     append=False,
                                     lastChunk=True
        )
        async with self.lock:
            if task.history is None:
                task.history = []
            task.history.append(response_artifact)

        msg_end = """这个流程图展示了一个标准的请假流程：
                            1、员工提交请假申请
                            2、部门经理进行审批
                            3、审批结果判断（通过 / 驳回）
                            4、如果驳回，申请返回员工修改
                            5、如果通过，人力资源进行备案
                            6、流程结束
                            你可以根据需要调整节点和流程，或者添加更多细节（如不同类型假期的分支、多级审批等）。
                            """
        for chunk in text_generator(msg_end, chunk_size=5):
            event_message = {'type': 'message', 'text': chunk}
            await self._emit_status_event(
                task,
                TaskState.WORKING,
                event_message,
                final=False
            )
            await asyncio.sleep(0.001)

        parts.append(TextPart(text=msg_end))

        response_message = Message(
            messageId=str(uuid4()),
            role="agent",
            parts=parts,
            contextId=task.contextId,
            taskId=task.id,
            kind='message'
        )

        # 添加AI回复到历史记录
        async with self.lock:
            if task.history is None:
                task.history = []
            task.history.append(response_message)

    async def form_event(self, task: Task):
        """
        处理第一次交互 - 返回input-required状态
        """
        logger.info("第一次交互 - 返回input-required状态询问菜系偏好")
        parts = []

        # 创建询问菜系偏好的消息
        inquiry_text = """欢迎使用食谱推荐服务！🍽️

为了给您推荐最合适的菜谱，请告诉我您偏好的菜系："""

        await self._emit_status_event(
            task,
            TaskState.WORKING,
            inquiry_text,
            final=False
        )
        await asyncio.sleep(0.001)
        parts.append(TextPart(text=inquiry_text))

        # 创建符合A2A协议的表单数据结构
        form_data = {
            "form": {
                "formId": "cuisine_preference_form",
                "title": "菜系偏好选择",
                "description": "请选择您偏好的菜系类型，我将为您推荐相应的美食菜谱",
                "fields": [
                    {
                        "name": "cuisine_type",
                        "type": "radio",
                        "label": "请选择您偏好的菜系",
                        "required": True,
                        "options": [
                            {
                                "value": "chinese",
                                "label": "🥢 中式菜系 - 川菜、粤菜、湘菜、鲁菜等"
                            },
                            {
                                "value": "western",
                                "label": "🍝 西式菜系 - 意大利菜、法式菜、美式菜等"
                            },
                            {
                                "value": "asian",
                                "label": "🍜 亚洲菜系 - 日式、韩式、泰式、印度菜等"
                            },
                            {
                                "value": "vegetarian",
                                "label": "🥗 素食健康 - 素食和健康轻食菜品"
                            }
                        ]
                    },
                    {
                        "name": "dietary_restrictions",
                        "type": "checkbox",
                        "label": "饮食限制（可选）",
                        "required": False,
                        "options": [
                            {
                                "value": "spicy",
                                "label": "不吃辣"
                            },
                            {
                                "value": "vegetarian",
                                "label": "素食主义"
                            },
                            {
                                "value": "low_sodium",
                                "label": "少盐饮食"
                            },
                            {
                                "value": "gluten_free",
                                "label": "无麸质饮食"
                            }
                        ]
                    },
                    {
                        "name": "difficulty_level",
                        "type": "select",
                        "label": "期望的制作难度",
                        "required": False,
                        "defaultValue": "medium",
                        "options": [
                            {
                                "value": "easy",
                                "label": "简单 - 30分钟内完成"
                            },
                            {
                                "value": "medium",
                                "label": "中等 - 1小时内完成"
                            },
                            {
                                "value": "hard",
                                "label": "复杂 - 需要较长时间和技巧"
                            }
                        ]
                    }
                ],
                "submitText": "获取食谱推荐",
                "cancelText": "取消",
                "layout": {
                    "columns": 1,
                    "spacing": "normal",
                    "direction": "vertical"
                }
            }
        }
        metadata = {"dataType": "form"}
        event_message = {"data": form_data}
        await self._emit_status_event(
            task,
            TaskState.WORKING,
            event_message,
            metadata=metadata,
            final=False
        )
        await asyncio.sleep(0.001)

        parts.append(DataPart(data=form_data, metadata=metadata))

        # 更新会话状态
        self.update_session_state(task.contextId, {
            "conversation_stage": "awaiting_cuisine_selection"
        })

        logger.info("已返回input-required状态，等待用户选择菜系")

        response_message = Message(
            messageId=str(uuid4()),
            role="agent",
            parts=parts,
            contextId=task.contextId,
            taskId=task.id,
            kind='message'
        )

        # 添加AI回复到历史记录
        async with self.lock:
            if task.history is None:
                task.history = []
            task.history.append(response_message)

    async def form_interactive_event(self, task: Task, user_text: str, form_data: Dict[str, Any]):
        """
        处理后续交互 - 正常处理用户请求
        """
        logger.info(f"后续交互 - 处理用户菜系选择: {user_text}")

        # 发送解析状态
        await self._emit_status_event(task, TaskState.WORKING, "正在解析您的菜系偏好...", final=False)
        await asyncio.sleep(0.001)

        # 从当前消息中解析表单数据或使用文本输入
        cuisine_info = self._parse_cuisine_preference(user_text, form_data)

        logger.info(f"解析到的菜系信息: {cuisine_info}")

        # 更新会话状态
        self.update_session_state(task.contextId, {
            "cuisine_preference": cuisine_info["cuisine_type"],
            "dietary_restrictions": cuisine_info.get("dietary_restrictions", []),
            "difficulty_level": cuisine_info.get("difficulty_level", "medium"),
            "conversation_stage": "recipe_recommendation"
        })

        # 发送生成状态
        cuisine_name = self._get_cuisine_name(cuisine_info["cuisine_type"])
        await self._emit_status_event(task, TaskState.WORKING, f"正在为您推荐{cuisine_name}的食谱...", final=False)
        await asyncio.sleep(0.001)

        # 使用流式生成食谱推荐（返回完整内容用于历史记录）
        await self._generate_recipe_recommendation_stream(task, cuisine_info, user_text)

        logger.info("食谱推荐完成")

    def _parse_cuisine_preference(self, user_text: str, form_data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """解析用户的菜系偏好"""
        result = {
            "cuisine_type": "chinese",  # 默认值
            "dietary_restrictions": [],
            "difficulty_level": "medium"
        }

        # 优先使用表单数据
        if form_data:
            result["cuisine_type"] = form_data.get("cuisine_type", "chinese")
            result["dietary_restrictions"] = form_data.get("dietary_restrictions", [])
            result["difficulty_level"] = form_data.get("difficulty_level", "medium")
            return result

        # 回退到文本解析
        user_text_lower = user_text.lower()

        if any(keyword in user_text_lower for keyword in ['中式', '中国', '川菜', '粤菜', '湘菜', '鲁菜', '中餐']):
            result["cuisine_type"] = "chinese"
        elif any(keyword in user_text_lower for keyword in ['西式', '意大利', '法式', '美式', '西餐', '意式']):
            result["cuisine_type"] = "western"
        elif any(keyword in user_text_lower for keyword in ['日式', '韩式', '泰式', '印度', '日本', '韩国', '泰国']):
            result["cuisine_type"] = "asian"
        elif any(keyword in user_text_lower for keyword in ['素食', '健康', '轻食', '蔬菜']):
            result["cuisine_type"] = "vegetarian"

        return result

    def _get_cuisine_name(self, cuisine_type: str) -> str:
        """获取菜系中文名称"""
        cuisine_names = {
            "chinese": "中式菜系",
            "western": "西式菜系",
            "asian": "亚洲菜系",
            "vegetarian": "素食健康"
        }
        return cuisine_names.get(cuisine_type, "中式菜系")

    async def _generate_recipe_recommendation_stream(self, task: Task, cuisine_info: Dict[str, Any], user_input: str):
        """使用流式接口根据菜系类型和偏好生成食谱推荐"""

        cuisine_type = cuisine_info["cuisine_type"]
        dietary_restrictions = cuisine_info.get("dietary_restrictions", [])
        difficulty_level = cuisine_info.get("difficulty_level", "medium")

        # 构建针对菜系的系统提示
        cuisine_prompts = {
            "chinese": "请推荐3-5道经典中式菜谱，包括川菜、粤菜或其他中式菜系。",
            "western": "请推荐3-5道经典西式菜谱，包括意大利菜、法式菜或美式菜。",
            "asian": "请推荐3-5道亚洲菜谱，如日式、韩式、泰式或印度菜。",
            "vegetarian": "请推荐3-5道健康素食菜谱，注重营养搭配。"
        }

        cuisine_prompt = cuisine_prompts.get(cuisine_type, cuisine_prompts["chinese"])

        # 构建饮食限制提示
        restrictions_text = ""
        if dietary_restrictions:
            restrictions_map = {
                "spicy": "不要辣味",
                "vegetarian": "纯素食",
                "low_sodium": "少盐清淡",
                "gluten_free": "无麸质"
            }
            restrictions = [restrictions_map.get(r, r) for r in dietary_restrictions]
            restrictions_text = f"特别注意：{', '.join(restrictions)}。"

        # 构建难度提示
        difficulty_map = {
            "easy": "简单易做，30分钟内完成",
            "medium": "中等难度，1小时内完成",
            "hard": "可以包含复杂技巧和较长制作时间"
        }
        difficulty_text = difficulty_map.get(difficulty_level, "中等难度")

        try:
            # 构建完整提示
            full_prompt = f"""
{self.system_prompt}

用户通过表单选择了菜系偏好，现在需要具体的食谱推荐。

用户选择信息:
- 菜系类型: {cuisine_type}
- 饮食限制: {dietary_restrictions}
- 难度偏好: {difficulty_level}
- 原始输入: {user_input}

{cuisine_prompt}
制作难度要求：{difficulty_text}
{restrictions_text}

请为每道菜提供：
1. 菜名
2. 主要食材清单
3. 简要制作步骤
4. 预计制作时间
5. 难度等级
6. 营养特点

请用友好的语调回答，让用户感到专业和贴心。如果有饮食限制，请特别说明如何满足这些要求。
"""

            # 使用流式接口调用AI模型
            stream = await self.ai_client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": full_prompt}
                ],
                temperature=0.7,
                max_tokens=1500,
                stream=True  # 启用流式响应
            )

            all_chunk_content = ""
            async for chunk in stream:
                if chunk.choices[0].delta.content is not None:
                    chunk_content = chunk.choices[0].delta.content
                    all_chunk_content += chunk_content
                    await self._emit_status_event(task, TaskState.WORKING, chunk_content, final=False)
                    await asyncio.sleep(0.001)

            response_message = Message(
                messageId=str(uuid4()),
                role="agent",
                parts=[TextPart(text=all_chunk_content)],
                contextId=task.contextId,
                taskId=task.id,
                kind='message'
            )

            # 添加AI回复到历史记录
            async with self.lock:
                if task.history is None:
                    task.history = []
                task.history.append(response_message)
        except Exception as e:
            logger.error(f"生成食谱推荐失败: {str(e)}")
            cuisine_name = self._get_cuisine_name(cuisine_type)
            msg = f"抱歉，生成{cuisine_name}推荐时遇到问题。请稍后再试，或者尝试其他菜系。错误信息：{str(e)}"
            await self._emit_status_event(task, TaskState.WORKING, msg, final=False)
            await asyncio.sleep(0.001)
